package com.xywy.find;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.broadcast.RemindBroadCast;
import com.xywy.broadcast.RemindService;
import com.xywy.common.BaseActivity;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.find.adapter.RemindAdapter;
import com.xywy.find.bean.Remind;
import com.xywy.me.bean.UserKeeper;
import com.xywy.start.widget.wheel.ArrayWheelAdapter;
import com.xywy.start.widget.wheel.OnWheelChangedListener;
import com.xywy.start.widget.wheel.WheelView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * 提醒 - 提醒添加
 * 
 * @author xiaogd
 * 
 */
public class RemindAddActivity extends BaseActivity {
	private static final String TAG = "RemindAddActivity";
	private LinearLayout layout = null;
	private WheelView yearWV = null;
	private WheelView monthWV = null;
	private WheelView dayWV = null;
	private TextView tvGo;
	private Context mContex;
	int year;
	int month;

	// 滚轮上的数据，字符串数组
	String[] yearArrayString = null;
	String[] dayArrayString = null;
	String[] monthArrayString = null;
	Calendar c = null;
	String dateStr;

	int[] weekDayCheck; // 选择的重复数据
	private TextView repet;
	private TextView type;
	private TextView tvBack;
	private Remind remindType; // 类型选择页面返回的数据

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.find_remind_add);
		this.preInit();
		this.initView();
		this.loadData();
		this.setListener();
	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.find_remind_add_title_bar);
		TextView tvTitle = titleBar.getTitle();
		tvBack = titleBar.getTvBack();
		tvGo = titleBar.getGo();
		titleBar.onClickBack(this);
		tvTitle.setText(getString(R.string.find_remind_add));
		tvBack.setText(getString(R.string.find_4));
		tvGo.setText(getString(R.string.find_remind_save));

		repet = (TextView) findViewById(R.id.tv_find_remind_add_repetv);
		type = (TextView) findViewById(R.id.tv_find_remind_add_typetv);

		// 日期滚动
		layout = (LinearLayout) findViewById(R.id.ll_find_remind_add);
		// 得到相应的数组
		yearArrayString = getYEARArray(2010, 19);
		monthArrayString = getDayArray(24);

		// 获取当前系统时间
		c = Calendar.getInstance();

		yearWV = (WheelView) findViewById(R.id.time_year);
		monthWV = (WheelView) findViewById(R.id.time_month);
		dayWV = (WheelView) findViewById(R.id.time_day);

		// 设置每个滚轮的行数
		yearWV.setVisibleItems(5);
		monthWV.setVisibleItems(5);
		dayWV.setVisibleItems(5);

		yearWV.setCyclic(true);
		monthWV.setCyclic(true);
		dayWV.setCyclic(true);
		setData();
		if (remindType != null && remindType.getTime() != null) {
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(remindType.getTime());
			monthWV.setCurrentItem(getNumData(c.get(Calendar.HOUR_OF_DAY) + "",
					monthArrayString));
			dayWV.setCurrentItem(getNumData(c.get(Calendar.MINUTE) + "",
					dayArrayString));
		}
	}

	/**
	 * 事件处理
	 * 
	 * @param view
	 */
	public void onClickRemindAdd(View view) {
		Class cl = null;
		switch (view.getId()) {
		case R.id.rl_find_remind_repet:
			cl = RemindRepetActivity.class;
			break;
		case R.id.rl_find_remind_fytx:
			cl = RemindTypeActivity.class;
			break;
		}
		;
		Intent intent = new Intent(this, cl);
		if (remindType == null)
			remindType = new Remind();
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, monthWV.getCurrentItem() + 1);
		c.set(Calendar.MINUTE, dayWV.getCurrentItem() + 1);
		remindType.setTime(c.getTimeInMillis());
		intent.putExtra("remindType", remindType);
		startActivity(intent);
	}

	@Override
	public void preInit() {
		mContex = this.context;
		Intent intent = this.getIntent();
		weekDayCheck = intent.getIntArrayExtra("weekofday");
		remindType = (Remind) intent.getSerializableExtra("remindType");
		if (null != remindType) {
			MLog.i(TAG, "从类型选择页返回的数据:" + remindType.toString());
			remindType.getTime();
		}
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(this).getUserid();
	}

	private String repetStr = "";
	private String dayStr;
	private String str = "每周";

	@Override
	public void loadData() {
		getWeekOfDay();
		if (null != remindType) {
			MLog.i(TAG, "从类型选择页返回的数据:" + remindType.toString());
			type.setText(remindType.getHint());
			repet.setText(RemindAdapter.repetDay(remindType.getLooparray()));
		}
	}

	private void getWeekOfDay() {
		int j = 0; // 记录选中的有多少天
		if (weekDayCheck != null && weekDayCheck.length > 0) {
			// 取出进行判断
			for (int i = 0; i < weekDayCheck.length; i++) {
				int ch = weekDayCheck[i];
				// MLog.i(TAG, "哪些天被选中" + ch);
				switch (i) {
				case 0:
					dayStr = str + "日 ";
					if (ch == 1) {
						repetStr += dayStr;
						j += 1;
					}
					break;
				case 1:
					dayStr = str + "一 ";
					if (ch == 1) {
						repetStr += dayStr;
						j += 1;
					}
					break;
				case 2:
					dayStr = str + "二 ";
					if (ch == 1) {
						repetStr += dayStr;
						j += 1;
					}
					break;
				case 3:
					dayStr = str + "三 ";
					if (ch == 1) {
						repetStr += dayStr;
						j += 1;
					}
					break;
				case 4:
					dayStr = str + "四 ";
					if (ch == 1) {
						repetStr += dayStr;
						j += 1;
					}
					break;
				case 5:
					dayStr = str + "五 ";
					if (ch == 1) {
						repetStr += dayStr;
						j += 1;
					}
					break;
				case 6:
					dayStr = str + "六 ";
					if (ch == 1) {
						repetStr += dayStr;
						j += 1;
					}
					break;
				}
			}

			if (repetStr != "") {
				if (j == weekDayCheck.length) {
					repetStr = getString(R.string.find_remind_day);
				}
				MLog.i(TAG, "选择每周中的哪些天:" + repetStr);
				repet.setText(repetStr);
			} else {
				Toast.makeText(mContex, "请选择重复时间", Toast.LENGTH_SHORT).show();
				return;
			}
		}
	}

	/**
	 * 给滚轮提供数据
	 */
	private void setData() {
		// 给滚轮提供数据
		yearWV.setAdapter(new ArrayWheelAdapter<String>(yearArrayString));
		monthWV.setAdapter(new ArrayWheelAdapter<String>(monthArrayString));

		yearWV.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// 获取年和月
				year = Integer.parseInt(yearArrayString[yearWV.getCurrentItem()]);
				month = Integer.parseInt(monthArrayString[monthWV
						.getCurrentItem()]);
				// 根据年和月生成天数数组
				dayArrayString = getDayArray(60);
				// 给天数的滚轮设置数据
				dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
				// 防止数组越界
				if (dayWV.getCurrentItem() >= dayArrayString.length) {
					dayWV.setCurrentItem(dayArrayString.length - 1);
				}
				// 显示的时间
				showDate();
			}
		});

		// 当月变化时显示的时间
		monthWV.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// 获取年和月
				year = Integer.parseInt(yearArrayString[yearWV.getCurrentItem()]);
				month = Integer.parseInt(monthArrayString[monthWV
						.getCurrentItem()]);
				// 根据年和月生成天数数组
				dayArrayString = getDayArray(60);
				// 给天数的滚轮设置数据
				dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
				// 防止数组越界
				if (dayWV.getCurrentItem() >= dayArrayString.length) {
					dayWV.setCurrentItem(dayArrayString.length - 1);
				}
				// 显示的时间
				showDate();
			}
		});

		// 当天变化时，显示的时间
		dayWV.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				showDate();
			}
		});

		// 把当前系统时间显示为滚轮默认时间
		setOriTime();
	}

	// 设定初始时间
	void setOriTime() {
		yearWV.setCurrentItem(getNumData(c.get(Calendar.YEAR) + "",
				yearArrayString));
		monthWV.setCurrentItem(getNumData(c.get(Calendar.HOUR_OF_DAY) + "",
				monthArrayString) + 0);

		dayArrayString = getDayArray(60);
		dayWV.setAdapter(new ArrayWheelAdapter<String>(dayArrayString));
		dayWV.setCurrentItem(getNumData(c.get(Calendar.MINUTE) + "",
				dayArrayString));

		// 初始化显示的时间
		showDate();
	}

	// 显示时间
	void showDate() {
		createDate(yearArrayString[yearWV.getCurrentItem()],
				monthArrayString[monthWV.getCurrentItem()],
				dayArrayString[dayWV.getCurrentItem()]);
	}

	// 生成时间
	void createDate(String year, String month, String day) {
		dateStr = year + "-" + month + "-" + day;
	}

	// 在数组Array[]中找出字符串s的位置
	int getNumData(String s, String[] Array) {
		int num = 0;
		for (int i = 0; i < Array.length; i++) {
			if (s.equals(Array[i])) {
				num = i;
				break;
			}
		}
		return num;
	}

	// 根据当前年份和月份判断这个月的天数
	public int getDay(int year, int month) {
		int day;
		if (year % 4 == 0 && year % 100 != 0) { // 闰年
			if (month == 1 || month == 3 || month == 5 || month == 7
					|| month == 8 || month == 10 || month == 12) {
				day = 31;
			} else if (month == 2) {
				day = 29;
			} else {
				day = 30;
			}
		} else { // 平年
			if (month == 1 || month == 3 || month == 5 || month == 7
					|| month == 8 || month == 10 || month == 12) {
				day = 31;
			} else if (month == 2) {
				day = 28;
			} else {
				day = 30;
			}
		}
		return day;
	}

	// 根据数字生成一个字符串数组
	public String[] getDayArray(int day) {
		String[] dayArr = new String[day];
		for (int i = 0; i < day; i++) {
			if (i == (day - 1))
				dayArr[i] = "00";
			else
				dayArr[i] = i + 1 + "";
		}
		return dayArr;
	}

	// 根据数字生成一个字符串数组
	public String[] getHMArray(int day) {
		String[] dayArr = new String[day];
		for (int i = 0; i < day; i++) {
			dayArr[i] = i + "";
		}
		return dayArr;
	}

	// 根据初始值start和step得到一个字符数组，自start起至start+step-1
	public String[] getYEARArray(int start, int step) {
		String[] dayArr = new String[step];
		for (int i = 0; i < step; i++) {
			dayArr[i] = start + i + "";
		}
		return dayArr;
	}

	private void setListener() {
		tvBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(RemindAddActivity.this,
						RemindListActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				finish();
			}
		});

		tvGo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// 发送网络请求
				sendMsg();
			}
		});
	}

	String webpwd;
	MyProgress myProgress;
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			webpwd = (String) msg.obj;
		}
	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;
	private SharedPreferences sp;
	private String userid;

	// 处理网络请求
	public void sendMsg() {

		// myProgress = new MyProgress(this,10);
		// myProgress.start();
		// paramsParser = new Parser();
		//
		// //封装参数
		// params = new HashMap<String, Object>();
		//
		// //请求路径
		// paramsParser.action = getString(R.string.find_upload_remind);
		// //请求方式
		// paramsParser.request = "post";
		//
		// SharedPreferences sp = mContex.getSharedPreferences("config",
		// mContex.MODE_PRIVATE);
		// String userid = sp.getString("userid","");
		//
		// //请求参数
		// params.put("userid", userid);
		//
		//
		// JSONArray jsonArray =null;
		//
		// //如果等于永不,则类型为2 [1.每周重复提醒，2.一次性提醒]
		// if(repet.getText().toString().equals(getString(R.string.find_remind_none))){
		// jsonArray = setJSONData(2);
		// }else{
		// jsonArray = setJSONData(1);
		// }
		// params.put("tiplist", jsonArray);
		// paramsParser.map = params;
		// //传递上下文
		// paramsParser.context = this.context;
		//
		// asyncHttpClient = AsyncHttpClient.getInstance();
		// asyncHttpClient.exeute(paramsParser,onResultListenerAdapter);
		// if(repet.getText().toString().equals(getString(R.string.find_remind_none))){
		// remindType.setHourmin(1840+"");
		// remindType.setLooparray(weekDayCheck);
		// remindType.setTime(System.currentTimeMillis());
		// remindType.setContentid(1);
		// remindType.setBelongs(1);
		// }else{
		// remindType.setBelongs(2);
		// remindType.setContentid(2);
		// remindType.setTime(System.currentTimeMillis());
		// }
//		if (repet == null || repet.getHint() == null
//				|| "".equals(repet.getHint())) {
//			Toast.makeText(this, "请选择提醒时间", 1).show();
//			return;
//		}
		if (remindType == null || remindType.getHint() == null
				|| "".equals(remindType.getHint())) {
			Toast.makeText(this, "请选择提醒类型", 1).show();
			return;
		}
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, monthWV.getCurrentItem() + 1);
		c.set(Calendar.MINUTE, dayWV.getCurrentItem() + 1);
		remindType.setTime(c.getTimeInMillis());
		System.out.println("时间差 "
				+ (System.currentTimeMillis() - remindType.getTime()));
		List<Remind> reminds = FileUtil.getList(userid + "reminds");
		remindType.setTogglet(true);
		reminds.add(remindType);
		FileUtil.saveObjectList(userid + "reminds", reminds);
		startAlarm();
		Intent intent = new Intent(RemindAddActivity.this,
				RemindListActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}
	};

	/**
	 * 封装上传的JSON数据
	 * 
	 * @return
	 * 
	 */
	private JSONArray setJSONData(int type) {
		JSONArray jsonArray = new JSONArray();
		try {
			JSONObject json = new JSONObject();
			json.put("type", type);

			int belongs = 1;
			int contentid = 1;
			if (type == 1) {
				JSONObject object = new JSONObject();
				object.put("hourmin", 1840);
				object.put("looparray", weekDayCheck);
				json.put("time", object);
			}
			if (type == 2) {
				belongs = 2;
				contentid = 2;
				json.put("time", System.currentTimeMillis()); // 当前的时间戳
			}
			json.put("belongs", belongs);
			json.put("contentid", contentid);
			json.put("hint", remindType.getHint());
			json.put("detail", remindType.getDetail());
			jsonArray.put(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonArray;
	}

	private void startAlarm() {
		// Intent intent = new Intent(this,
		// RemindBroadCast.class);
		// intent.setAction(RemindBroadCast.REMINDACTION);
		// PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent,
		// Intent.FLAG_ACTIVITY_NEW_TASK);
		// long time = remindType.getTime();
		// AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		// am.setInexactRepeating(AlarmManager.RTC_WAKEUP, time,
		// 1000 * 60 * 60 * 24 * 7, pi);
		Intent intent = new Intent(this, RemindService.class);
		startService(intent);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		// super.onBackPressed();
		Intent intent = new Intent(RemindAddActivity.this,
				RemindListActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

}
